package com.xspace.android.imcommon.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.text.TextUtils;
import android.util.Log;

import com.xspace.android.imcommon.entity.ChatMsgSnap;
import com.xspace.android.xafcommon.util.DateUtils;
import com.xspace.android.xafcommon.util.StringUtils;

import java.util.ArrayList;

/**
 * MessageDb数据库
 * 
 * 
 */
public class ImUserDb extends BaseDb {

	public ImUserDb(Context context) {
		super(context);
	}

	public static final String TAG = "ImUserDb";
	/**
	 * _id
	 */
	public static final String _ID = "_id";
	/**
	 * 最新内容
	 */
	public static final String COLOUMN_LATEST_CONTENT = "latest_content";
	/**
	 * 最新内容类型 0：文本 1、图片 2、语音 3、视频
	 */
	public static final String COLOUMN_LATEST_CONTENT_TYPE = "latest_content_type";
	/**
	 * 最新消息发送时间
	 */
	public static final String COLOUMN_LATEST_SEND_TIME = "latest_send_time";
	/**
	 * 最新操作时间
	 */
	public static final String COLOUMN_LATEST_HANDLE_TIME = "latest_handle_time";
	/**
	 * 消息状态 0：发送中 1:发送成功 2 发送失败,3 接收
	 */
	public static final String COLOUMN_STATUS = "status";
	/**
	 * 消息条数
	 */
	public static final String COLOUMN_MSG_COUNT = "msg_count";
	/**
	 * 未读条数
	 */
	public static final String COLOUMN_UNREAD_COUNT = "read_count";
	/**
	 * 发送消息的barejid
	 */
	public static final String COLOUMN_BAREJID = "barejid";
	/**
	 * 发送消息的uuid
	 */
	public static final String COLOUMN_UUID = "uuid";
	/**
	 * 消息所属人
	 */
	public static final String COLOUMN_OWNER = "owner";

	/**
	 * 消息所属人
	 */
	public static final String COLOUMN_USERNAME = "userName";
	public static final String COLOUMN_MSG_TYPE = "msg_type";
	/**
	 * 消息所属人
	 */
	public static final String COLOUMN_HREAD = "userHread";
	
	public static final String TABLE_NAME = "CHAT_MSG_SNAP";
	public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + _ID + " INTEGER primary key," + COLOUMN_LATEST_CONTENT + " CHAR(1000),"
			+ COLOUMN_MSG_TYPE + " INTEGER," 
			+ COLOUMN_LATEST_CONTENT_TYPE + " INTEGER," + COLOUMN_LATEST_SEND_TIME + " CHAR(128)," + COLOUMN_LATEST_HANDLE_TIME + " CHAR(128)," + COLOUMN_STATUS + " INTEGER,"
			+ COLOUMN_UNREAD_COUNT + " INTEGER," + COLOUMN_MSG_COUNT + " INTEGER," + COLOUMN_BAREJID + " CHAR(128)," + COLOUMN_UUID + " CHAR(128)," + COLOUMN_OWNER + " CHAR(128),"
			+ COLOUMN_USERNAME + " CHAR(128),"+ COLOUMN_HREAD + " CHAR(128))";

	@Override
	String getTableName() {
		return TABLE_NAME;
	}

	/**
	 * 保存消息数据
	 * 
	 * @return
	 */
	public int insertOrUpdateMsg(ChatMsgSnap chatMsgSnap) {
		ContentValues values = new ContentValues();
		values.put(COLOUMN_LATEST_CONTENT, chatMsgSnap.mLatestContent);
		values.put(COLOUMN_LATEST_CONTENT_TYPE, chatMsgSnap.mLatestContentType);
		values.put(COLOUMN_LATEST_SEND_TIME, chatMsgSnap.mLatestSendTime);
		values.put(COLOUMN_LATEST_HANDLE_TIME, DateUtils.getCurrentDatetimeString(DateUtils.FORMAT_1));
		values.put(COLOUMN_STATUS, chatMsgSnap.mStatus);
		values.put(COLOUMN_BAREJID, chatMsgSnap.mBarejid);
		values.put(COLOUMN_UUID, chatMsgSnap.mUUID);
		values.put(COLOUMN_OWNER, chatMsgSnap.mOwner);
		values.put(COLOUMN_MSG_TYPE, chatMsgSnap.msgType);
		System.out.println("-----------------------chatMsgSnap.mToUserName:"+chatMsgSnap.mToUserName);
		if(!StringUtils.isNull(chatMsgSnap.mToUserName))
		values.put(COLOUMN_USERNAME, chatMsgSnap.mToUserName);
		if(!TextUtils.isEmpty(chatMsgSnap.mHread)){
		values.put(COLOUMN_HREAD, chatMsgSnap.mHread);
		}
		String sql = "select * from " + TABLE_NAME + " where " + COLOUMN_BAREJID + " = '" + chatMsgSnap.mBarejid + "' and " + COLOUMN_OWNER + " = '" + chatMsgSnap.mOwner + "'";
		Cursor cursor = null;
		try {
			long rowId = -1;
			checkDb();
			cursor = db.rawQuery(sql, null);
			if (cursor != null && cursor.getCount() > 0) {
				if (chatMsgSnap.mStatus == 3) {
					cursor.moveToFirst();
					values.put(COLOUMN_UNREAD_COUNT, cursor.getInt(cursor.getColumnIndex(COLOUMN_UNREAD_COUNT)) + 1);
				}
				rowId = db.update(TABLE_NAME, values, COLOUMN_BAREJID + "=? and " + COLOUMN_OWNER + "=?", new String[] { chatMsgSnap.mBarejid + "", "" + chatMsgSnap.mOwner });
			} else {
				values.put(COLOUMN_UNREAD_COUNT, chatMsgSnap.mReadCount);
				rowId = db.insert(TABLE_NAME, null, values);
				Log.e(TAG, "insertOrUpdateMsg()... insert rowId: " + rowId);
			}
			return (int) rowId;
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		} finally {
			closeDbAndCursor(cursor);
		}
	}

	// 修改用户名称和头像
	public boolean doUpdateNameHead(String userId, String userName, String userHead, int userState) {
		try {
			checkDb();
			ContentValues cv = new ContentValues();
			if (!TextUtils.isEmpty(userName))
				cv.put(COLOUMN_USERNAME, userName);
			if (!TextUtils.isEmpty(userName))
				cv.put(COLOUMN_HREAD, userHead);
			cv.put(COLOUMN_STATUS, userState);
			int num = db.update(TABLE_NAME, cv, COLOUMN_BAREJID + "=?", new String[] { userId });
			Log.d(TAG, "updateByfddHouse_id data effected number:" + num);
			if (num > 0) {
				return true;
			}
			return false;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	// 修改信息状态
	public boolean doUpdateUnread(String userId, String fromUserId, int unread) {
		try {
			checkDb();
			ContentValues cv = new ContentValues();
			cv.put(COLOUMN_STATUS, unread);
			int num = db.update(TABLE_NAME, cv, COLOUMN_BAREJID + "=? and " + COLOUMN_OWNER + "=?", new String[] { userId + "", "" + fromUserId });
			Log.d(TAG, "updateByfddHouse_id data effected number:" + num);
			if (num > 0) {
				return true;
			}
			return false;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	// 修改信息状态
		public boolean doUpdateUnreadCount(String userId, String fromUserId, int unread) {
			try {
				checkDb();
				ContentValues cv = new ContentValues();
				cv.put(COLOUMN_UNREAD_COUNT, unread);
				int num = db.update(TABLE_NAME, cv, COLOUMN_BAREJID + "=? and " + COLOUMN_OWNER + "=?", new String[] { userId + "", "" + fromUserId });
				Log.d(TAG, "updateByfddHouse_id data effected number:" + num);
				if (num > 0) {
					return true;
				}
				return false;
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}

	/**
	 * 分页查询数据
	 * 
	 * @param state
	 * @return
	 */
	public ArrayList<ChatMsgSnap> findMsgList(String fromUserId, int startRecord, int pageSize) {
		ArrayList<ChatMsgSnap> dataList = new ArrayList<ChatMsgSnap>();
		String sql = "select * from " + TABLE_NAME + " where " + COLOUMN_OWNER + " ='" + fromUserId + "' order by " + COLOUMN_LATEST_SEND_TIME + " desc limit " + pageSize
				+ " offset " + startRecord;
        System.out.println("--------------------------sql:"+sql);
		Cursor cursor = null;
		try {
			checkDb();
			cursor = db.rawQuery(sql, null);
			if (cursor != null && cursor.getCount() > 0) {
				cursor.moveToFirst();
				for (int i = 0; i < cursor.getCount(); i++) {
					cursor.moveToPosition(i);
					ChatMsgSnap chatMsgSnap = new ChatMsgSnap();
					chatMsgSnap._id = cursor.getInt(cursor.getColumnIndex(_ID));
					chatMsgSnap.mBarejid = cursor.getString(cursor.getColumnIndex(COLOUMN_BAREJID));
					chatMsgSnap.mLatestContent = cursor.getString(cursor.getColumnIndex(COLOUMN_LATEST_CONTENT));
					chatMsgSnap.mLatestContentType = cursor.getInt(cursor.getColumnIndex(COLOUMN_LATEST_CONTENT_TYPE));
					chatMsgSnap.mLatestHandleTime = cursor.getString(cursor.getColumnIndex(COLOUMN_LATEST_HANDLE_TIME));
					chatMsgSnap.mLatestSendTime = cursor.getString(cursor.getColumnIndex(COLOUMN_LATEST_SEND_TIME));
					chatMsgSnap.mOwner = cursor.getString(cursor.getColumnIndex(COLOUMN_OWNER));
					chatMsgSnap.mMsgCount = cursor.getInt(cursor.getColumnIndex(COLOUMN_MSG_COUNT));
					chatMsgSnap.mReadCount = cursor.getInt(cursor.getColumnIndex(COLOUMN_UNREAD_COUNT));
					chatMsgSnap.mStatus = cursor.getInt(cursor.getColumnIndex(COLOUMN_STATUS));
					chatMsgSnap.mUUID = cursor.getString(cursor.getColumnIndex(COLOUMN_UUID));
					chatMsgSnap.mToUserName = cursor.getString(cursor.getColumnIndex(COLOUMN_USERNAME));
					chatMsgSnap.mHread= cursor.getString(cursor.getColumnIndex(COLOUMN_HREAD));
					chatMsgSnap.msgType=cursor.getInt(cursor.getColumnIndex(COLOUMN_MSG_TYPE));
					dataList.add(chatMsgSnap);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeDbAndCursor(cursor);
		}
		Log.d(TAG, sql + " , and find " + dataList.size());

		return dataList;
	}

	/**
	 * 查询数据
	 * 
	 * @param state
	 * @return
	 */
	public ChatMsgSnap findUserMsg(String toUserId, String fromUserId) {
		ChatMsgSnap entity = null;
		String sql = "select * from " + TABLE_NAME + " where " + COLOUMN_BAREJID + " ='" + toUserId + "' and  " + COLOUMN_OWNER + " ='" + fromUserId + "'";
		Log.d(TAG, "findUserMsg()... " + sql);
		Cursor cursor = null;
		try {
			checkDb();
			cursor = db.rawQuery(sql, null);
			if (cursor != null && cursor.getCount() > 0) {
				entity = new ChatMsgSnap();
				cursor.moveToFirst();
				entity._id = cursor.getInt(cursor.getColumnIndex(_ID));
				entity.mBarejid = cursor.getString(cursor.getColumnIndex(COLOUMN_BAREJID));
				entity.mLatestContent = cursor.getString(cursor.getColumnIndex(COLOUMN_LATEST_CONTENT));
				entity.mLatestContentType = cursor.getInt(cursor.getColumnIndex(COLOUMN_LATEST_CONTENT_TYPE));
				entity.mLatestHandleTime = cursor.getString(cursor.getColumnIndex(COLOUMN_LATEST_HANDLE_TIME));
				entity.mLatestSendTime = cursor.getString(cursor.getColumnIndex(COLOUMN_LATEST_SEND_TIME));
				entity.mOwner = cursor.getString(cursor.getColumnIndex(COLOUMN_OWNER));
				entity.mMsgCount = cursor.getInt(cursor.getColumnIndex(COLOUMN_MSG_COUNT));
				entity.mReadCount = cursor.getInt(cursor.getColumnIndex(COLOUMN_UNREAD_COUNT));
				entity.mStatus = cursor.getInt(cursor.getColumnIndex(COLOUMN_STATUS));
				entity.mUUID = cursor.getString(cursor.getColumnIndex(COLOUMN_UUID));
				entity.mToUserName = cursor.getString(cursor.getColumnIndex(COLOUMN_USERNAME));
				entity.mHread= cursor.getString(cursor.getColumnIndex(COLOUMN_HREAD));
			}
			return entity;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			closeDbAndCursor(cursor);
		}
	}

	/**
	 * 查询数据
	 * 
	 * @param state
	 * @return
	 */
	public int findUnreadAll(String fromUserId) {
		int sum = 0;
		String sql = "select  sum(" + COLOUMN_UNREAD_COUNT + ") from " + TABLE_NAME + " where " + COLOUMN_OWNER + " ='" + fromUserId + "'";
		Cursor cursor = null;
		try {
			checkDb();
			cursor = db.rawQuery(sql, null);
			if (cursor != null && cursor.getCount() > 0) {
				cursor.moveToFirst();
				sum = cursor.getInt(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeDbAndCursor(cursor);
		}
		Log.d(TAG, "findUnReadAll()... " + sql + ", and unread sum is " + sum);
		return sum;
	}

	/**
	 * 查找用户是否存在
	 * 
	 * @param state
	 * @return
	 */
	public boolean findMsg(String userId) {
		String sql = "select * from " + TABLE_NAME + " where " + COLOUMN_BAREJID + " ='" + userId + "'";
		Log.d(TAG, "findMsg()... " + sql);
		Cursor cursor = null;
		try {
			checkDb();
			cursor = db.rawQuery(sql, null);
			return (cursor != null && cursor.getCount() > 0);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			closeDbAndCursor(cursor);
		}
	}

	/**
	 * 查询用户数量
	 * 
	 * @param state
	 * @return
	 */
	public int findSize() {
		String sql = "select * from " + TABLE_NAME;
		Log.d(TAG, "findSize()... " + sql);
		Cursor cursor = null;
		try {
			checkDb();
			cursor = db.rawQuery(sql, null);
			if (cursor != null) {
				return cursor.getCount();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeDbAndCursor(cursor);
		}
		return 0;
	}

	public void clearAllData() {
		try {
			checkDb();
			String sql = "delete from " + TABLE_NAME + ";";
			db.execSQL(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	public boolean deleteUser(String userId, String fromUserId) {
		try {
			checkDb();
			String whereClause = String.format(" %s = ? and %s = ? ", COLOUMN_BAREJID, COLOUMN_OWNER);
			String[] whereArgs = new String[] { userId, fromUserId };
			int res = db.delete(TABLE_NAME, whereClause, whereArgs);
			return res > 0;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

}
